// makes an input box emulate a terminal.
// by Sandesh Singh (http://sandesh247.googlepages.com/)
// This is on googlecode, look up at what license is applicable.
// 
// 'internal' commands are commands that aren't process()ed or format()ted,
// they simply correspond to a javascript function.
// internal commands can be added thusly :
// $.fn.emulate_terminal.commands.whoa = function(o) { alert ('whoa!')};

// Wish list :
// * Command auto completion (workable with the autocomplete plugin)
// * Instance level commands
// * Proper command line parsing (GNU options style)

(function($){
  $.fn.emulate_terminal = function(options){
    var opts = $.extend({}, $.fn.emulate_terminal.defaults, options);
    
    return this.each(function(){
      var $this = $(this);
      var options = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
      options = $.extend({}, options, { input : $this })
      
      // Checks if the word is a command, and processes it if it is.
      // returns true if it is, false otherwise.
      var process_internal_cmd = function(cmd) {
        if($.fn.emulate_terminal.commands[cmd]){
          $.fn.emulate_terminal.commands[cmd](options);
          return true;
        }
        return false;
      }

      $this.keypress(function(e){
        var $this = $(this);
        if(e.which == 13 && $this.val() != ''){
          var value = $this.val();
          
          // Check if first word is a function, else jiggy wid it ...
          if(!process_internal_cmd(value.split(' ')[0])){
            if(options.process) value = options.process(value);
            if(options.format) value = options.format(value);
              
            if(options.output_id){
              var jhdid = $('#' + options.output_id);
              var sep = options.separator;
              
              jhdid
                .append(value)
                .append($.isFunction(sep) ? sep(options) : (sep ? sep : ''))
                .scrollTop(jhdid.height());
            }
          }

          // command done, clear it up ...
          // (should this be an option?)
          $this.val('');
        }
      })
    });
  }
  
  /* default options */
  $.fn.emulate_terminal.defaults = {
    process : function (x) { return x },
    format : function (x) { return '<div>' + x + '</div>' },
    separator : '--'
  }
  
  /* internal commands */
  $.fn.emulate_terminal.commands = {
    clear : function(obj) {
      if(obj.output_id)
        $('#' + obj.output_id).html('');
    }
  }
})(jQuery);
